package com.model;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.*;

@Component
@Scope("singleton")
public class DBBase {
    @Resource
    DBConnection dbConnection;


    public ResultSet selectAll(String sql) throws SQLException, ClassNotFoundException {
        Connection con = dbConnection.getCon();
        Statement statement = con.createStatement();
        return statement.executeQuery(sql);
    }

    public ResultSet selectOne(String sql,Object[] param) throws SQLException, ClassNotFoundException {
        Connection con = dbConnection.getCon();
        PreparedStatement statement = con.prepareStatement(sql);
        for(int i=1;i<=param.length;i++){
            statement.setObject(i, param[i-1]);
        }
        return statement.executeQuery();
    }

    public void InsertOne(String sql, Object[] param) throws SQLException, ClassNotFoundException {
        Connection con = dbConnection.getCon();
        PreparedStatement statement = con.prepareStatement(sql);
        for(int i=1;i<=param.length;i++){
            statement.setObject(i, param[i-1]);
        }
        statement.execute();
    }
    public void DeleteOne(String sql, Object[] param) throws SQLException, ClassNotFoundException {
        Connection con = dbConnection.getCon();
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        for(int i=1;i<=param.length;i++){
            preparedStatement.setObject(i,param[i-1]);
        }
        preparedStatement.execute();
    }
    public void UpdateOne(String sql, Object[] param) throws SQLException, ClassNotFoundException {
        Connection con = dbConnection.getCon();
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        for(int i=1;i<=param.length;i++){
            preparedStatement.setObject(i,param[i-1]);
        }
        preparedStatement.execute();
    }
}
